// packagePT/apply/apply.js
const app = getApp()
import WxValidate from '../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageInfo: {},
    recommendInfo: {},
    selectedUserId: '',
    formData: {
      name: '',
      mobile: '',
      areaText: '',
      areaValue: '',
      province_id: '',
      city_id: '',
      district_id: '',
      province: '',
      city: '',
      district: '',
      agree: false
    },
    areaOptions: [],
    areaShow: false,
    protocolShow: false,
    referenceShow: false,
    pageContainerShow: false,
    loading: false
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    const { readonly } = this.data
    if (readonly) return
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 注册区域选择确认
   * @param {Object} e 
   */
  areaFinish: function(e) {
    const { selectedOptions, value } = e.detail;
    const fieldValue =`${selectedOptions[0].text}-${selectedOptions[1].text}-${selectedOptions[2].text}` 
    this.setData({
      'formData.areaText': fieldValue,
      'formData.province_id': selectedOptions[0].value,
      'formData.city_id': selectedOptions[1].value,
      'formData.district_id': selectedOptions[2].value,
      'formData.province': selectedOptions[0].text,
      'formData.city': selectedOptions[1].text,
      'formData.district': selectedOptions[2].text,
      'formData.areaValue': selectedOptions[2].value,
      areaShow: false
    })
  },

  /**
   * 显示推荐人弹窗
   */
  showReference: function() {
    const { is_exist_recommend } = this.data.recommendInfo
    // 已存在推荐人
    if (is_exist_recommend) return
    this.setData({
      pageContainerShow: true
    });
  },

  /**
   * 关闭推荐人弹窗
   */
  hideReference() {
    this.setData({
      pageContainerShow: false
    })
  },

  /**
   * 推荐人选中
   * @param {Object} e 
   */
  seleceUser(e) {
    const { detail } = e
    this.setData({
      recommendInfo: {
        recommend_id: detail.uid,
        recommend_name: detail.uid_name,
        zhang_lv_id: detail.id,
        zhang_lv_name: detail.name
      },
      selectedUserId: detail.id,
      pageContainerShow: false
    })
  },

  /**
   * 协议勾选
   * @param {Object} e 
   */
  protocolChange: function(e) {
    this.setData({
      'formData.agree': e.detail
    })
  },

  /**
   * 显示协议
   */
  showProtocol: function() {
    this.setData({
      protocolShow: true
    })
  },

  /**
   * 阅读并同意协议
   */
  agreeProtocol: function() {
    this.setData({
      'formData.agree': true,
      protocolShow: false
    })
  },

  /**
   * 提交表单(立即支付)
   */
  submitForm: function() {
    if (!this.WxValidate.checkForm(this.data.formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    const { formData, recommendInfo} = this.data
    const {
      name,
      mobile,
      province,
      city,
      district,
      province_id,
      city_id,
      district_id,
    } = formData
    let data = {
      name,
      mobile,
      province,
      city,
      district,
      province_id,
      city_id,
      district_id,
    }
    // 推荐人
    if (recommendInfo.recommend_id) {
      data.recommend_id = recommendInfo.recommend_id
      data.recommend_type = recommendInfo.type
    }
    // 推荐人为掌旅
    if (recommendInfo.zhang_lv_id) {
      data.zhang_lv_id = recommendInfo.zhang_lv_id
      data.zhang_lv_name = recommendInfo.zhang_lv_name
    }
    const parames = {
      // tag: surcharge-附加费，expertDeposit-达人押金，guideDeposit-导游押金，palmTravel-掌旅入驻
      tag: 'palmTravelIn',
      // 创建支付信息route(必填)
      createRoute: 'plugin.company-manage.frontend.store.zhangLvPay.create',
      // 创建支付信息参数(如果接口没有参数可为{})
      createParames: data,
      // 余额支付route(必填)
      balancePayRoute: 'plugin.company-manage.frontend.store.zhangLvPay.credit2',
      // 微信支付route(必填)
      WeChatPayRoute: 'plugin.company-manage.frontend.store.zhangLvPay.wechatPay',
      // 支付成功跳转页面(必填)
      redirectPath: '/packageG/member_v2/member_v2',
      // 验证支付route(必填)
      ckeckPayRoute: 'plugin.company-manage.frontend.store.zhangLvPay.checkPay'
    }
    wx.navigateTo({
      url: '/packageFT/pay-surcharge/pay-surcharge?parames=' + encodeURIComponent(JSON.stringify(parames)),
    })
  },
  
  /**
  * 获取省市列表(区域)
  */
  getAddress: function() {
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("member.member-address.address");
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const thirdLevelRegion = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              const child2 = resData.data.district.filter(item2 => item2.parentid == item1.id).map(item2 => {
                return {
                  text: item2.areaname,
                  value: item2.id + ''
                }
              })
              return {
                text: item1.areaname,
                value: item1.id + '',
                children: child2
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          _this.setData({ 
            areaOptions: thirdLevelRegion
          })
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

 /**
  * 获取页面信息(掌旅封面、金额、协议)
  */
  getPageInfo: function() {
    const _this = this
    const urlStr = app.getNetAddresss('plugin.company-manage.frontend.store.zhangLv.getBasic')
    app._getNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({ pageInfo: resData.data })
        } else {
          app.tips('获取页面信息失败！')
        }
      },
    })
  },

  /**
   * 获取登陆用户的推荐人信息
   * @param {Object} options 页面传参
   */
  getRecommendInfo: function(options) {
    const _this = this
    const urlStr = app.getNetAddresss('member.member-info.getRecommendInfo')
    app._getNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const resultData = resData.data
          if (resultData.is_exist_recommend) {
            // 接口获取已经存在推荐人则使用接口获取的推荐人
            resultData.type = resultData.zhang_lv_id ? 3 : ''
            _this.setData({
              recommendInfo: resultData
            })
          } else {
            // 接口获取没有推荐人，则options获取推荐人信息
            _this.getRecommendByRecommendId(options)
          }
        } else {
          app.tips(resData.msg || '获取推荐人信息失败！')
        }
      }
    })
  },

  /**
   * 根据recommend_id获取推荐人信息
   * @param {Object} options
   */
  getRecommendByRecommendId: function(options) {
    let recommend_id = ''
    if (options.recommend_id) {
      // 通过分享进入页面，参数存在recommend_id则直接使用
      recommend_id = options.recommend_id
    } else if(options.scene) {
      // 扫码进入页面
      const scene = decodeURIComponent(options.scene)
      const info_arr = scene.split(",")
      const info_arr1 = info_arr[1].split("&")
      info_arr1.forEach(item => {
        const itemKey = item.split('=')[0]
        const itemValue = item.split('=')[1]
        if(itemKey == 'recommend_id' && itemValue) {
          recommend_id = itemValue
        }
      })
    }
    if (!recommend_id) {
      return
    }
    const _this = this
    wx.showLoading({ title: '获取推荐人信息...' })
    app._getNetWork({
      url: app.getNetAddresss('plugin.company-manage.frontend.store.zhangLv.getUserInfo'),
      data: { recommend_id },
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const { recommend_id, recommend_name, zhang_lv_id, zhang_lv_name } = resData.data
          _this.setData({
            recommendInfo: {
              recommend_id, recommend_name, zhang_lv_id, zhang_lv_name,
              is_exist_recommend: 1
            }
          })
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 绑定会员上下级关系
   * @param {Object} options 
   */
  bindRelation: function(options) {
    let recommend_id = ''
    if (options.recommend_id) {
      // 通过分享进入页面，参数存在recommend_id则直接使用
      recommend_id = options.recommend_id
    } else if(options.scene) {
      // 扫码进入页面
      const scene = decodeURIComponent(options.scene)
      const info_arr = scene.split(",")
      const info_arr1 = info_arr[1].split("&")
      info_arr1.forEach(item => {
        const itemKey = item.split('=')[0]
        const itemValue = item.split('=')[1]
        if(itemKey == 'recommend_id' && itemValue) {
          recommend_id = itemValue
        }
      })
    }
    if (!recommend_id) {
      return
    }
    app._getNetWork({
      url: app.getNetAddresss('plugin.company-manage.frontend.store.zhangLv.bindRelation'),
      data: { recommend_id }
    })
  },

 /**
  * 初始化表单验证
  */
 initValidate: function() {
  const { pageInfo } = this.data
  const rules = {
    name: {
      required: true
    },
    mobile: {
      required: true,
      tel: true
    },
    areaText: {
      required: true
    },
    agree: {
      isTrue: pageInfo.protocol_status
    }
  }
  const message = {
    name: {
      required: '请输入掌旅姓名'
    },
    mobile: {
      required: '请输入手机号',
      tel: '请输入正确的手机号码'
    },
    areaText: {
      required: '请选择区域'
    },
    agree: {
      isTrue: '请阅读并同意协议'
    }
  }
  this.WxValidate = new WxValidate(rules, message)
  this.WxValidate.addMethod('isTrue', (value) => {
    return Boolean(value)
  })
 },

 /**
  * 验证是否为掌旅
  * @param {Object} options 页面传参
  */
  isExistZhangLv: function(options) {
    const _this = this
    wx.showLoading({ title: '正在验证...'})
    app._getNetWork({
      url: app.getNetAddresss('plugin.company-manage.frontend.store.zhangLv.isExistZhangLv'),
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          if (resData.data == 1) {
            // 已经是掌旅，跳转到掌旅管理
            setTimeout(() => {
              app.tips('您已经是掌旅！')
            })
            setTimeout(() => {
              wx.redirectTo({
                url: '/packageG/pages/member/plamTravel/plamTravel',
              })
            }, 2500)
          } else {
            _this.initValidate()
            _this.getAddress()
            _this.getPageInfo()
            _this.getRecommendInfo(options)
            _this.bindRelation(options)
          }
        } else {
          app.tips(resData.msg || '验证失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.isExistZhangLv(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})